package com.cn.codebrush.链表;

public class No19删除链表的倒数第N个结点 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        l1.next = node1;
        node1.next=node2;
        node2.next=node3;
        node3.next=node4;

        System.out.println(removeNthFromEnd(l1,2));
    }

    /**
     * 208 / 208 个通过测试用例
     * 倒数第几个  可以想象成  正数第几个
     * @param head
     * @param n
     * @return
     */
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode temp = head;
        int k = 0;
        while (temp != null){
            temp = temp.next;
            k++;
        }

        int q = k-n; //要删的前一个
        if(q == 0){
            return head.next;
        }

        ListNode pre = head;
        for(int i=1;i<=k;i++){
            if(i == q){
                pre.next = pre.next.next;
                break;
            }
            pre = pre.next;
        }
        return head;
    }
}
